package cn.bellychang.deferredresult;

import com.codahale.metrics.Counter;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.MetricRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * @author ChangLiang
 * @date 2020/2/21
 */
@RestController
public class HelloWorldController {

    private final static MetricRegistry REGISTRY = new MetricRegistry();

    private final static JmxReporter REPORTER = JmxReporter.forRegistry(REGISTRY)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    private static final BlockingDeque<Long> queue = new LinkedBlockingDeque<>(1_1000);

    private final static Counter queueCounter = new Counter();

    static{
        REGISTRY.register("queue-counter", queueCounter);
        REPORTER.start();
    }

    @GetMapping("/hello")
    public String index() {
        return "hello world";
    }

    @GetMapping("/addTask")
    public String addTask() {
        long nanoTime = System.nanoTime();
        queue.add(nanoTime);
        queueCounter.inc();
        return "add a task " + nanoTime;
    }

    @GetMapping("/pollTask")
    public String pollTask() {
        long nanoTime = queue.poll();
        if (queue.poll() != null) {
            queueCounter.dec();
        }
        return "poll a task " + nanoTime;
    }
}
